package com.yzc.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * 创建数据库连接
 * @author sanzang
 *
 */
public class DbUtil {
	
	static String url = "jdbc:mysql://localhost:3306/c1901?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
    static String name = "root";
	static String pass="123456";
	
	// 获取一个连接
	public static Connection getConn() {
		Connection	conn=null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		   	conn = DriverManager.getConnection(url,name,pass);
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return conn;
	}
	
	public static List selectTable(String sql,Class c) throws Exception{
		List list = new ArrayList();
		Connection conn= DbUtil.getConn();
		PreparedStatement pt =  conn.prepareStatement(sql);
		ResultSet rs =  pt.executeQuery();
		//得到查询的字段名 --元数据
		ResultSetMetaData rsd = rs.getMetaData();
		int cols = rsd.getColumnCount();
		while(rs.next()) {
			Object obj = c.newInstance();
			for(int i=1;i<=cols;i++) {
				String name = rsd.getColumnName(i);
				Object val = rs.getObject(name);
				Field f= c.getDeclaredField(name);
				f.set(obj, val);
			} 
			list.add(obj);  //放入集合
		}
		conn.close();
		return list;
	}
	
}
